<template>
  <PageLayout title="消息中心" description="管理你的通知和消息">
    <!-- 错误提示 -->
    <div v-if="error" class="mb-6 p-4 bg-error/20 text-error rounded-lg border border-error/30">
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span class="font-medium">加载失败</span>
        </div>
        <p class="mt-1 text-sm">{{ error }}</p>
        <div class="mt-3">
          <UiButton variant="secondary" size="sm" @click="retryLoad">
            重试
          </UiButton>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <!-- 侧边栏 -->
        <div class="lg:col-span-1">
          <div class="bg-background-800 rounded-xl p-4 border border-gray-700">
            <h3 class="text-lg font-medium text-text-primary mb-4">消息类型</h3>
            <div class="space-y-2">
              <button
                class="w-full text-left px-3 py-2 rounded-lg transition-colors duration-normal"
                :class="activeTab === 'messages' ? 'bg-primary text-white' : 'text-text-primary hover:bg-background-700'"
                @click="activeTab = 'messages'"
              >
                <div class="flex items-center gap-2">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                  </svg>
                  消息列表
                  <span 
                    v-if="unreadCount > 0"
                    class="ml-auto px-2 py-0.5 text-xs bg-error text-white rounded-full"
                  >
                    {{ unreadCount }}
                  </span>
                </div>
              </button>
              
              <button
                class="w-full text-left px-3 py-2 rounded-lg transition-colors duration-normal"
                :class="activeTab === 'settings' ? 'bg-primary text-white' : 'text-text-primary hover:bg-background-700'"
                @click="activeTab = 'settings'"
              >
                <div class="flex items-center gap-2">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  设置
                </div>
              </button>
            </div>


          </div>
        </div>

        <!-- 主内容区域 -->
        <div class="lg:col-span-3">
          <div class="bg-background-800 rounded-xl border border-gray-700 overflow-hidden">
            <!-- 消息列表 -->
            <div v-if="activeTab === 'messages'" class="flex flex-col">
              <!-- 头部操作栏 -->
              <div class="flex items-center justify-between p-4 border-b border-gray-700">
                <div class="flex items-center gap-4">
                  <h2 class="text-lg font-bold text-text-primary">消息</h2>
                  <div class="flex items-center gap-2">
                    <UiButton
                      :variant="filter === 'all' ? 'secondary' : 'ghost'"
                      size="sm"
                      @click="setFilter('all')"
                    >
                      全部 ({{ messages.length }})
                    </UiButton>
                    <UiButton
                      :variant="filter === 'unread' ? 'secondary' : 'ghost'"
                      size="sm"
                      @click="setFilter('unread')"
                    >
                      未读 ({{ unreadMessages.length }})
                    </UiButton>
                  </div>
                </div>
                
                <!-- 右侧操作按钮 -->
                <div class="flex items-center gap-2">
                  <UiButton
                    v-if="unreadCount > 0"
                    variant="primary"
                    size="sm"
                    @click="markAllAsRead"
                    :loading="markingAllAsRead"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    全部已读
                  </UiButton>
                  <UiButton
                    variant="secondary"
                    size="sm"
                    @click="refreshMessages"
                    :loading="loading"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    刷新消息
                  </UiButton>
                </div>
              </div>

              <!-- 消息内容（随页面滚动，无内部滚动条） -->
              <div>
                <!-- 加载状态 -->
                <div v-if="loading && filteredMessages.length === 0" class="flex flex-col items-center justify-center py-12">
                  <LoadingSpinner />
                  <p class="text-text-muted mt-4">加载消息中...</p>
                </div>

                <!-- 消息列表 -->
                <div v-else-if="filteredMessages.length > 0" class="divide-y divide-border">
                  <MessageItem
                    v-for="message in filteredMessages"
                    :key="message.id"
                    :message="message"
                    @mark-as-read="handleMarkAsRead"
                    @delete="handleDelete"
                    @click="handleMessageClick"
                  />
                </div>

                <!-- 空状态 -->
                <div v-else class="flex flex-col items-center justify-center py-12 text-center">
                  <div class="w-16 h-16 bg-background-700 rounded-full flex items-center justify-center mb-4">
                    <svg class="w-8 h-8 text-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                    </svg>
                  </div>
                  <h3 class="text-lg font-medium text-text-primary mb-2">
                    {{ filter === 'unread' ? '没有未读消息' : '暂无消息' }}
                  </h3>
                  <p class="text-sm text-text-muted mb-4">
                    {{ filter === 'unread' ? '所有消息都已阅读' : '当你收到新消息时会在这里显示' }}
                  </p>
                  <div class="flex gap-2">
                    <UiButton
                      variant="secondary"
                      size="sm"
                      @click="refreshMessages"
                      :loading="loading"
                    >
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                      </svg>
                      刷新
                    </UiButton>
                    <UiButton
                      variant="ghost"
                      size="sm"
                      @click="createTestMessage"
                      :loading="creating"
                    >
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                      创建测试消息
                    </UiButton>
                  </div>
                </div>

                <!-- 底部加载指示（已有内容时加载更多的过渡提示） -->
                <div v-if="loading && filteredMessages.length > 0" class="flex justify-center p-4">
                  <LoadingSpinner />
                </div>

                <!-- 无限下拉哨兵：进入视口时自动触发 loadMore -->
                <div
                  v-if="hasMore && filteredMessages.length > 0"
                  ref="infiniteSentinel"
                  class="h-6"
                />
              </div>
            </div>

            <!-- 设置（无内部滚动条） -->
            <div v-else-if="activeTab === 'settings'">
              <MessageSettings />
            </div>
          </div>
        </div>
      </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useMessages } from '../composables/useMessages'
import { useUserStore } from '../store/useUserStore'
import PageLayout from '../components/layout/PageLayout.vue'
import MessageSettings from '../components/messages/MessageSettings.vue'
import MessageItem from '../components/messages/MessageItem.vue'
import { UiButton, LoadingSpinner } from '../components/ui'
import type { MessageWithDetails } from '../types/messages'
import { runMessageSystemTest } from '../utils/testMessages'

// 状态
const activeTab = ref<'messages' | 'settings'>('messages')
const filter = ref<'all' | 'unread'>('all')
const creating = ref(false)
const markingAllAsRead = ref(false)
const testing = ref(false)
const infiniteSentinel = ref<HTMLElement | null>(null)
let intersectionObserver: IntersectionObserver | null = null

// 使用消息composable
const { 
  messages, 
  unreadMessages,
  unreadCount, 
  loading, 
  error, 
  hasMore,
  createMessage, 
  loadMessages,
  loadMore,
  markAsRead,
  markAllAsRead: markAllAsReadApi,
  deleteMessage,
  init 
} = useMessages()

// 使用用户store
const userStore = useUserStore()
const { user, isAuthenticated } = userStore

// 计算属性
const currentUserId = computed(() => user?.id)
const filteredMessages = computed(() => {
  return filter.value === 'unread' ? unreadMessages.value : messages.value
})

// 设置过滤器
const setFilter = (newFilter: 'all' | 'unread') => {
  filter.value = newFilter
  loadMessages(newFilter === 'unread', true)
}

// 刷新消息
const refreshMessages = async () => {
  await loadMessages(filter.value === 'unread', true)
}

// 重试加载
const retryLoad = async () => {
  await init()
}

// 创建测试消息
const createTestMessage = async () => {
  // 若未检测到用户，尝试主动获取一次会话
  if (!currentUserId.value) {
    await userStore.getCurrentUser()
    if (!userStore.user?.id) {
      // 未登录则弹出登录框
      userStore.openLoginModal()
      return
    }
  }

  const recipientId = currentUserId.value || userStore.user!.id

  creating.value = true
  try {
    const result = await createMessage({
      recipient_id: recipientId,
      type: 'system',
      title: '测试消息',
      content: '这是一条测试消息，用于验证消息系统是否正常工作。'
    })

    if (result.success) {
      // 刷新消息列表
      await loadMessages(filter.value === 'unread', true)
    } else {
      const { useUiStore } = await import('../store/useUiStore')
      useUiStore().showError(result.error || '创建失败')
    }
  } catch (error) {
    console.error('Error creating test message:', error)
    const { useUiStore } = await import('../store/useUiStore')
    useUiStore().showError('创建测试消息失败')
  } finally {
    creating.value = false
  }
}

// 标记消息为已读
const handleMarkAsRead = async (messageId: number) => {
  const result = await markAsRead(messageId)
  if (!result.success) {
    console.error('Failed to mark message as read:', result.error)
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  markingAllAsRead.value = true
  try {
    const result = await markAllAsReadApi()
    if (result.success) {
      // 显示成功提示
      const { useUiStore } = await import('../store/useUiStore')
      const uiStore = useUiStore()
      uiStore.showSuccess('所有消息已标记为已读')
    } else {
      console.error('Failed to mark all messages as read:', result.error)
      // 显示错误提示
      const { useUiStore } = await import('../store/useUiStore')
      const uiStore = useUiStore()
      uiStore.showError(result.error || '标记失败')
    }
  } finally {
    markingAllAsRead.value = false
  }
}

// 删除消息
const handleDelete = async (messageId: number) => {
  const result = await deleteMessage(messageId)
  if (!result.success) {
    console.error('Failed to delete message:', result.error)
  }
}

// 处理消息点击
const handleMessageClick = (message: MessageWithDetails) => {
  // 可以在这里添加点击消息的逻辑，比如导航到相关页面
  console.log('Message clicked:', message)
}

// 运行系统测试
const runSystemTest = async () => {
  testing.value = true
  try {
    const result = await runMessageSystemTest()
    if (result.success) {
      alert(`系统测试成功！创建了 ${result.created} 条测试消息`)
      await refreshMessages()
    } else {
      alert(`系统测试失败: ${result.error}`)
    }
  } catch (error) {
    console.error('Error running system test:', error)
    alert('系统测试失败')
  } finally {
    testing.value = false
  }
}

// 初始化
onMounted(async () => {
  await init()

  // 设置 IntersectionObserver 实现无限下拉
  const setupObserver = () => {
    if (intersectionObserver) {
      intersectionObserver.disconnect()
      intersectionObserver = null
    }
    if (!infiniteSentinel.value) return

    intersectionObserver = new IntersectionObserver((entries) => {
      const entry = entries[0]
      if (entry && entry.isIntersecting && hasMore.value && !loading.value) {
        loadMore(filter.value === 'unread')
      }
    }, { threshold: 0.1 })

    intersectionObserver.observe(infiniteSentinel.value)
  }

  await nextTick()
  setupObserver()

  // 当筛选结果或更多状态变化时，重新绑定哨兵
  watch([() => hasMore.value, () => filteredMessages.value.length], async () => {
    await nextTick()
    setupObserver()
  })
})

onBeforeUnmount(() => {
  if (intersectionObserver) {
    intersectionObserver.disconnect()
    intersectionObserver = null
  }
})
</script>
